package 字符串;

/**
 * @Author Weton Li
 * @Date 2021/8/28 16:40
 */
public class 删除字符串中相邻重复项 {
    public static void main(String[] args) {
        String input = "abbaca";
        System.out.println(removeDuplicates(input));
    }

    public static String removeDuplicates(String s) {
        StringBuffer stack = new StringBuffer();
        int top = -1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (top == -1) {
                stack.append(c);
                top++; // top=0
                continue;
            }
            if (c == stack.charAt(top)) {
                stack.deleteCharAt(top);
                top--;
                continue;
            }
            if (c != stack.charAt(top)) {
                stack.append(c);
                top++;
            }
        }
        return stack.toString();
    }
}
